import React from 'react';
import {injectIntl} from 'react-intl';
import {Form, Input, Button, TimePicker, message, Table, Row, Col, Spin} from 'antd';
import axios from 'axios';
import {withRouter} from 'react-router-dom';
import PopTask from './popTask'
import Grid from '../../components/table/grid'
import moment from "moment/moment";

const FormItem = Form.Item;
const createForm = Form.create;

@withRouter
class AddTask extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            modalSwitch: false,
            selectRows: [],
            loading:false,
            refresh:0
        };
        const common = this.props.intl.messages.common;
        this.columns = [
            {
                title: common.EquipmentNo,
                dataIndex: 'id',
                key: 'id',
            },
            {
                title: common.powerStationName,
                dataIndex: 'name',
                key: 'name',
            },
            {
                title: common.operation,
                dataIndex: 'operation',
                key: 'operation',
                render: (text, record) => (
                    <span>
                    <a onClick={() => this.onDelete(record.id)}>{common.delete}</a>
                </span>
                ),
            }
        ]
        this.columns2 = [
            {
                title: common.EquipmentNo,
                dataIndex: 'stubId',
                key: 'stubId',
            },
            {
                title: common.powerStationName,
                dataIndex: 'stubGroupName',
                key: 'stubGroupName',
            },
            {
                title: common.operation,
                dataIndex: 'operation',
                key: 'operation',
                render: (text, record) => (
                    <span>
                    <a onClick={() => this.realDelete(record.stubId)}>{common.delete}</a>
                </span>
                ),
            }
        ]
    }

    onDelete = (id) => {

        const dataSource = [...this.state.selectRows];
        this.setState({selectRows: dataSource.filter(item => item.id !== id)});
    };

    freshTable=()=>{
        this.setState({
            refresh:this.state.refresh+1
        })
    }
    realDelete = (id) => {
        const common = this.props.intl.messages.common;
        let params = {
            "planId": this.props.location.state.info.id,
            "stubIds": id,
            "type": 2
        };
        this.setState({
            loading:true,
        });

        axios.post(`/api/plan/stub/mod`, {...params}).then(res => {
            this.setState({
                loading:false
            });

            if(res&&res.data&&res.data.code==200){
                message.success(common.OperateSuccessfully);
                this.setState({
                    refresh:this.state.refresh+1
                })
            }
        })
    }

    closeModal = () => {
        this.setState({
            modalSwitch: false,
        });
    }


    handleSubmit = (e) => {
        e.preventDefault();
        const common = this.props.intl.messages.common;
        this.props.form.validateFieldsAndScroll((err, values) => {
            if (!!err) {
                console.log('fail');
                return;
            }
            this.setState({
                loading:true
            });
            values.startTime = values.startTime.format('HH:mm');
            values.stubIds = this.state.selectRows.map((item) => {
                return item.id
            }).join(',');
            values.type = 1;
            axios.post('/api/plan/create', {...values}).then(res => {
                this.setState({
                    loading:false
                });
                if (res && res.data) {
                    if (res.data.code == 200) {
                        message.success(common.OperateSuccessfully);
                    }
                    this.props.history.goBack();
                }
            });
        });
    };

    componentWillMount() {
        if (!this.props.location.state) {
            this.props.history.goBack();
        }
    }

    saveSelectRows = (data) => {
        this.setState({
            selectRows: data
        }, () => {
            console.log(this.state.selectRows)
        })
    }

    render() {
        if (!this.props.location.state) {
            this.props.history.replace('/monitor/monitorPlan');
            return null
        }
        const common = this.props.intl.messages.common;
        // const config = {
        //     rules: [{required: true, message: common.notEmpty},
        //     ],
        //     validateTrigger: 'onBlur',
        //     // initialValue:this.props.selectAccount.name,
        // };
        // const timeConfig = {
        //     rules: [{type: 'object', required: true, message: common.notEmpty}],
        // };
        const {getFieldDecorator} = this.props.form;
        const formItemLayout = {
            labelCol: {
                xl: {span: 4},
                xxl: {span: 4}
            },
            wrapperCol: {
                xl: {span: 18},
                xxl: {span: 20}
            },
        };
        const tailFormItemLayout = {
            wrapperCol: {
                xl: {
                    span: 24,
                    offset: 4,
                },
                xxl: {
                    span: 16,
                    offset: 4,
                },
            },
        };

        const isModify = this.props.location.state.status === "modify";
        const isAdd = this.props.location.state.status === "add";
        const info = this.props.location.state.info;
        return (
            <Row>
                <Col xxl={10} xl={15}>
                    <Spin tip="Loading..." spinning={this.state.loading}>
                    <form form={this.props.form} onSubmit={this.handleSubmit}>
                        <FormItem
                            {...formItemLayout}
                            label={common.taskName}
                        >
                            {getFieldDecorator('name', {
                                    rules: [{required: true, message: common.notEmpty},
                                    ],
                                    initialValue:info?info.name:'',
                                    validateTrigger: 'onBlur'}
                            )(
                                <Input style={{maxWidth: 250}} disabled={isModify}/>
                            )}
                        </FormItem>
                        <FormItem
                            {...formItemLayout}
                            label={common.actingTime}
                        >
                            {getFieldDecorator('startTime', {rules: [{type: 'object', required: true, message: common.notEmpty}],initialValue:info?moment(info.startTime, 'HH:mm'):undefined})(
                                <TimePicker format={'HH:mm'} disabled={isModify}/>
                            )}
                        </FormItem>
                        <FormItem
                            {...formItemLayout}
                            label={common.actingEquip}
                        >
                            <Button onClick={() => {
                                this.setState({modalSwitch: true})
                            }}>{common.selectEquip}</Button>
                        </FormItem>
                        <Row>
                            <Col xl={{offset: 4}} xxl={{offset: 4}}>
                                {(isAdd && this.state.selectRows.length > 0) &&
                                <Table style={{marginBottom: 12}} dataSource={this.state.selectRows}
                                       columns={this.columns} rowKey={record => record.id} bordered={true}
                                       pagination={false} size={'middle'}/>}
                                {isModify &&
                                <Grid refresh={this.state.refresh} style={{marginBottom: 12}} columns={this.columns2} url="/api/plan/stub/qry"
                                      params={{planId: info.id}} rowKey={record => record.stubId}/>}
                            </Col>
                        </Row>
                        {isAdd && <FormItem {...tailFormItemLayout}>
                            <Button type="primary" htmlType="submit">{common.save}</Button>
                        </FormItem>}
                    </form>
                    <PopTask visible={this.state.modalSwitch}
                             onCancel={this.closeModal}
                             selectedInfo={this.state.selectedInfo}
                             saveSelectRows={this.saveSelectRows}
                             freshTable={this.freshTable}
                    />
                    </Spin>
                </Col>
            </Row>
        )
    }
}

AddTask = createForm()(AddTask);
export default injectIntl(AddTask);